package org.liuh.t2020.netty.httpserver01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @Description TODO
 * @Author liuh
 */
public class TestHttpServerHandle extends SimpleChannelInboundHandler<HttpObject> {


    /**
     * @Description TODO 针对HTTP范型. 设置为HttpObject。
     * @Author liuh
     * @Date 2020/1/12
     * @Params * @param null
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {

            // 构造响应内容. TODO ByteBuf是及其重要的类！！
            ByteBuf content = Unpooled.copiedBuffer("Hello, Netty", CharsetUtil.UTF_8);
            // 创建响应对象
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, content);
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 返回结果. 如果仅仅调用write. 会设置到缓存区. 与ServletAPI方式比较！
            // servletApi 直接使用response对象进行返回结果. response.write()； 这里使用ctx类进行操作.
            ctx.writeAndFlush(fullHttpResponse);
        }
    }
}
